package kubayaxi.video.service.base.util.tengxun;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Service
@Slf4j
public class TXFileUtil {
    @Autowired
    private COSClient myCosClient;

    // 存放文件的存储桶
    final static String bucketName = "lmusic-1302280959";

    /**
     * 上传小文件 20M - 5G
     */
    public String upload(MultipartFile file,String prePath) {
        // 获取文件名
        //获取文件名称（可能包含路径）
        String fileName = file.getOriginalFilename();
        //获取最后"/"的索引
        int startIndex = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
        //截取文件名，根据业务，文件后缀也可去掉
        fileName = fileName.substring(startIndex + 1);
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = prePath+fileName;
        InputStream inputStream = null;
        try{
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream,null);
        PutObjectResult putObjectResult = myCosClient.putObject(putObjectRequest);
        String preUrl = "https://lmusic-1302280959.cos.ap-chengdu.myqcloud.com/";
        return preUrl + prePath + fileName;
    }

    public String uploadFile(File file, String prePath) {
        // 获取文件名
        //获取文件名称（可能包含路径）
        String fileName = file.getName();
        //获取最后"/"的索引
        int startIndex = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
        //截取文件名，根据业务，文件后缀也可去掉
        fileName = fileName.substring(startIndex + 1);
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = prePath+fileName;

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        PutObjectResult putObjectResult = myCosClient.putObject(putObjectRequest);
        String preUrl = "https://lmusic-1302280959.cos.ap-chengdu.myqcloud.com/";
        return preUrl + prePath + fileName;
    }
}
